<!-- 班次时令 -->
<template>
  <div class="classes-season" v-loading="loading">
    <el-tabs v-model="activeName" type="card" style="height:100%" class="class-tabs">
      <el-tab-pane label="夏令时" name="summer">
        <el-scrollbar style="height:100%">
          <timeSetting
            ref="summer"
            :season-obj.sync="summerObj"
            season-name="summer"
            @importData="importData('winter')"
          >
            <el-checkbox slot="isdefault" v-model="isDefaultSummer" @change="changeDefault('summer')" border size="small" class="isdefault">默认时令</el-checkbox>
          </timeSetting>
        </el-scrollbar>
      </el-tab-pane>
      <el-tab-pane label="冬令时" name="winter">
        <el-scrollbar style="height:100%">
          <timeSetting
            ref="winter"
            :season-obj.sync="winterObj"
            season-name="winter"
            @importData="importData('summer')"
          >
            <el-checkbox slot="isdefault" v-model="isDefaultWinter" @change="changeDefault('winter')" border size="small" class="isdefault">默认时令</el-checkbox>
          </timeSetting>
        </el-scrollbar>
      </el-tab-pane>
    </el-tabs>
    <div class="buttons">
      <!-- <el-checkbox v-model="continuityNum">连续号源
        <el-tooltip class="item" effect="dark" content="连续号源：设置号源排班时，号源的号码为连续号码" placement="top-end">
          <i class="el-icon-question"></i>
        </el-tooltip>
      </el-checkbox> -->
      <el-button class="save-button" @click="cancle">撤销</el-button>
      <el-button type="primary" class="save-button" @click="saveBtn">提交</el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import timeSetting from './timeSetting'
import { setHospitalSetting, getHospitalSetting } from '@/api/api.js'
import bus from '@/api/bus'
export default {
  name: 'ShiftsInSeason',
  mixins: [],
  components: { timeSetting },
  props: {
    hospitalCode: {
      type: String,
      default: ''
    },
    depArea: {
      type: String,
      default: ''
    },
    dep: {
      type: String,
      default: ''
    },
    getId: {
      type: Function,
      default: () => {}
    }
  },
  data() {
    return {
      loading: false,
      activeName: 'summer',
      obj: {
        hospitalCode: this.hospitalCode,
        seasonSettings: {
          夏令时: {
            startMonth: 5,
            startDay: 1,
            endMonth: 9,
            endDay: 30,
            checkClassSettings: {
              上午班: {
                startHour: 8,
                startMinute: 0,
                endHour: 12,
                endMinute: 0,
                defaultMinute: 30,
                numberSettings: [
                  {
                    startHour: 8,
                    startMinute: 0,
                    endHour: 12,
                    endMinute: 0,
                    preKey: 'A',
                    startNum: 1
                  }
                ]
              },
              下午班: {
                startHour: 1,
                startMinute: 30,
                endHour: 5,
                endMinute: 0,
                defaultMinute: 30,
                numberSettings: [
                  {
                    startHour: 1,
                    startMinute: 30,
                    endHour: 5,
                    endMinute: 0,
                    preKey: 'B',
                    startNum: 1
                  }
                ]
              }
            }
          },
          冬令时: null
        }
      },
      summerObj: {},
      winterObj: {},
      originData: {
        summer: null,
        winter: null
      },
      // continuityNum: false,
      isDefaultWinter: false,
      isDefaultSummer: true
    }
  },
  watch: {
    hospitalCode(val) {
      this.getHospitalData()
    },
    depArea(val) {
      console.log('depArea=>val', val)
      // val == '' && this.getHospitalData()
      this.getHospitalData()
    },
    dep(val) {
      this.getHospitalData()
    }
  },
  computed: {
    ...mapGetters(['setTimeTip'])
  },
  created() {
    bus.$off('getHospitalData')
    bus.$on('getHospitalData', () => {
      console.log('getHospitalData')
      this.getHospitalData()
    })
  },
  mounted() {
    // this.getHospitalData()
  },
  methods: {
    getHospitalData() {
      this.loading = true
      let params = {
        HospitalCode: this.hospitalCode,
        depArea: this.depArea,
        dep: this.dep
      }
      getHospitalSetting(params).then((val) => {
        this.loading = false
        if (val) {
          this.summerObj = val.content ? val.content.seasonSettings.夏令时 : null
          this.winterObj = val.content ? val.content.seasonSettings.冬令时 : null
          this.originData.summer = JSON.parse(JSON.stringify(this.summerObj))
          this.originData.winter = JSON.parse(JSON.stringify(this.winterObj))
          // this.continuityNum = this.summerObj.continuityNum
          this.isDefaultWinter = this.winterObj.isDefault
          this.isDefaultSummer = this.summerObj.isDefault
          const depArea = val.content.depArea || ''
          const dep = val.content.dep || ''
          console.log('val.content.seasonRuleId', val.content.seasonRuleId)
          this.$emit('getId', val.content.seasonRuleId || '')
          if (depArea != this.depArea && dep != this.dep) {
            bus.$emit('tiggerDeleteBtn', false)
            this.$alert(`[${this.depArea}-${this.dep}]未设置时令，当前默认使用了医院统一的时令，若您想单独给[${this.depArea}-${this.dep}]设置时令，在医院统一的时令下进行"编辑-提交"即可`, '系统提示', {
              confirmButtonText: '确定'
            })
          } else if (depArea != this.depArea && this.dep == '') {
            bus.$emit('tiggerDeleteBtn', false)
            this.$alert(`[${this.depArea}]未设置时令，当前默认使用了医院统一的时令，若您想单独给[${this.depArea}]设置时令，在医院统一的时令下进行"编辑-提交"即可`, '系统提示', {
              confirmButtonText: '确定'
            })
          } else if (this.depArea == '' && dep != this.dep) {
            bus.$emit('tiggerDeleteBtn', false)
            this.$alert(`[${this.dep}]未设置时令，当前默认使用了医院统一的时令，若您想单独给[${this.dep}]设置时令，在医院统一的时令下进行"编辑-提交"即可`, '系统提示', {
              confirmButtonText: '确定'
            })
          } else if (this.depArea == depArea && dep != this.dep) {
            bus.$emit('tiggerDeleteBtn', false)
            this.$alert(`[${this.dep}]未设置时令，当前默认使用了[${this.depArea}]的时令，若您想单独给[${this.dep}]设置时令，在[${this.depArea}]的时令下进行"编辑-提交"即可`, '系统提示', {
              confirmButtonText: '确定'
            })
          } else if (this.depArea == '' && dep == this.dep) {
            bus.$emit('tiggerDeleteBtn', true)
            // this.$alert(`[${this.dep}]未设置时令，当前默认使用了医院统一的时令，若您想单独给[${this.dep}]设置时令，在医院统一的时令下进行"编辑-提交"即可`, '系统提示', {
            //   confirmButtonText: '确定'
            // })
          } else if (this.depArea == '' && this.dep == '') {
            bus.$emit('tiggerDeleteBtn', false)
          } else {
            bus.$emit('tiggerDeleteBtn', true)
          }
        }
      })
    },
    saveBtn() {
      this.$confirm(`${this.setTimeTip}请确认是否要更改当前时令?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.save()
        // this.$message({
        //   type: 'success',
        //   message: '删除成功!'
        // })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消更改'
        })
      })
    },
    save() {
      let dataObj = {
        hospitalCode: this.hospitalCode,
        depArea: this.depArea,
        dep: this.dep,
        seasonSettings: {
          夏令时: {},
          冬令时: {}
        }
      }
      this.isValidate().then(() => {
        let isTimeError = false
        let summerObj = this.getData(this.$refs.summer)
        let winterObj = this.getData(this.$refs.winter)
        if (summerObj.endMonth == winterObj.startMonth) {
          if (summerObj.endDay == winterObj.startDay) {
            isTimeError = true
            this.$alert(`夏时令的${summerObj.endMonth}月${summerObj.endDay}号与冬时令的${winterObj.startMonth}月${winterObj.startDay}号重叠，请不要选择同一天`, '系统提示', {
              confirmButtonText: '确定'
            })
          }
          if (summerObj.endDay > winterObj.startDay) {
            isTimeError = true
            this.$alert(`夏时令的${summerObj.endMonth}月${summerObj.endDay}号结束与冬时令的${winterObj.startMonth}月${winterObj.startDay}号开始存在冲突，请合理调整时间`, '系统提示', {
              confirmButtonText: '确定'
            })
          }
        }
        if (winterObj.endMonth == summerObj.startMonth) {
          if (winterObj.endDay == summerObj.startDay) {
            isTimeError = true
            this.$alert(`冬时令的${winterObj.endMonth}月${winterObj.endDay}号与夏时令的${summerObj.startMonth}月${summerObj.startDay}号重叠，请不要选择同一天`, '系统提示', {
              confirmButtonText: '确定'
            })
          }
          if (winterObj.endDay > summerObj.startDay) {
            isTimeError = true
            this.$alert(`冬时令的${winterObj.endMonth}月${winterObj.endDay}号结束与夏时令的${summerObj.startMonth}月${summerObj.startDay}号开始存在冲突，请合理调整时间`, '系统提示', {
              confirmButtonText: '确定'
            })
          }
        }
        this.isDefaultSummer = !this.isDefaultSummer && !this.isDefaultWinter ? true : this.isDefaultSummer
        summerObj.isDefault = this.isDefaultSummer
        winterObj.isDefault = this.isDefaultWinter
        dataObj.seasonSettings.夏令时 = summerObj
        dataObj.seasonSettings.冬令时 = winterObj
        if (!isTimeError) {
          setHospitalSetting(dataObj).then((res) => {
            if (res.code === 10000) {
              this.originData.summer = JSON.parse(JSON.stringify(summerObj))
              this.originData.winter = JSON.parse(JSON.stringify(winterObj))
              this.$message({
                type: 'success',
                message: '保存成功'
              })
              this.getHospitalData()
            }
          })
        }
      }).catch(() => {

      })
    },
    cancle() {
      /* 撤销 */
      this.summerObj = JSON.parse(JSON.stringify(this.originData.summer))
      this.winterObj = JSON.parse(JSON.stringify(this.originData.winter))
      // this.continuityNum = this.summerObj.continuityNum
    },
    isValidate() {
      /* 判断数据是否填写完整 */
      return new Promise((rs, rj) => {
        let flag1
        this.$refs.summer.isValidate((flag) => {
          if (!flag) {
            this.activeName = 'summer'
          }
          flag1 = flag
        })
        let flag2
        this.$refs.winter.isValidate((flag) => {
          if (!flag) {
            this.activeName = 'winter'
          }
          flag2 = flag
        })
        if (flag1 && flag2) {
          rs()
        } else {
          rj()
        }
      })
    },
    getData(temp) {
      let data = {}
      let summerDay = temp.formData.seasonDate
      // data.continuityNum = this.continuityNum
      data.startMonth = Number(summerDay[0].split('-')[0])
      data.startDay = Number(summerDay[0].split('-')[1])
      data.endMonth = Number(summerDay[1].split('-')[0])
      data.endDay = Number(summerDay[1].split('-')[1])
      data.checkClassSettings = {}
      let list = temp.formData.timeLists
      list.forEach(v => {
        data.checkClassSettings[v.name] = {}
        data.checkClassSettings[v.name].startHour = Number(v.amTimes[0].split(':')[0]) !== 24 ? Number(v.amTimes[0].split(':')[0]) : 23
        data.checkClassSettings[v.name].startMinute = Number(v.amTimes[0].split(':')[0]) !== 24 ? Number(v.amTimes[0].split(':')[1]) : 59
        data.checkClassSettings[v.name].endHour = Number(v.amTimes[1].split(':')[0]) !== 24 ? Number(v.amTimes[1].split(':')[0]) : 23
        data.checkClassSettings[v.name].endMinute = Number(v.amTimes[1].split(':')[0]) !== 24 ? Number(v.amTimes[1].split(':')[1]) : 59
        data.checkClassSettings[v.name].defaultMinute = v.defaultMinute
        data.checkClassSettings[v.name].numberSettings = v.numberSettings
        v.numberSettings.forEach(el => {
          el.startHour = el.startTime ? Number(el.startTime.split(':')[0]) !== 24 ? Number(el.startTime.split(':')[0]) : 23 : 0
          el.startMinute = el.startTime ? Number(el.startTime.split(':')[0]) !== 24 ? Number(el.startTime.split(':')[1]) : 59 : 0
          el.endHour = el.endTime ? Number(el.endTime.split(':')[0]) !== 24 ? Number(el.endTime.split(':')[0]) : 23 : 0
          el.endMinute = el.endTime ? Number(el.endTime.split(':')[0]) !== 24 ? Number(el.endTime.split(':')[1]) : 59 : 0
        })
      })
      return data
    },
    importData(fromType) {
      let confirmMsg = `确定要赋值${fromType === 'summer' ? '夏令时' : '冬令时'}的班次数据吗？`
      this.$confirm(confirmMsg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (fromType === 'summer') {
          // this.$refs.winter.seasonDate = this.$refs.summer.seasonDate
          this.$refs.winter.formData.timeLists = JSON.parse(JSON.stringify(this.$refs.summer.formData.timeLists))
        } else {
          // this.$refs.summer.seasonDate = this.$refs.winter.seasonDate
          this.$refs.summer.formData.timeLists = JSON.parse(JSON.stringify(this.$refs.winter.formData.timeLists))
        }
        this.$message.success('导入完成')
      })
    },
    changeDefault(fromType) {
      if (fromType === 'summer') {
        this.isDefaultWinter = !this.isDefaultSummer
      } else {
        this.isDefaultSummer = !this.isDefaultWinter
      }
    }
  },
  beforeDestroy() {
    bus.$off('getHospitalData')
  },
  destroyed() {},
  beforeUpdate() {},
  updated() {}
}
</script>
<style lang='scss' scoped>
.classes-season{
    width:100%;
    height: 100%;
    .el-tabs /deep/ .el-tabs__nav{
        margin-left: 16px;
    }
    .buttons{
        width: 100%;
        position: fixed;
        right: 0;
        bottom: 0;
        background: #FFFFFF;
        border: 1px solid #E8E8E8;
        padding: 10px;
        text-align: right;
        .save-button{
            margin: 0 10px;
        }
        .el-button--primary{
            background: #00C0EF;
        }
    }
}
.isdefault{
  margin-left: 20px;
}
.el-tabs /deep/ .el-tabs__item.is-top.is-active{
    background: #00C0EF;
    color: #fff;
}
.el-tabs /deep/ .el-tabs__item{
    border-radius: 5px 5px 0 0;
}
.class-tabs{
    height:100%;
    /deep/ .el-tabs__content{
        height: calc(100% - 104px);
        // overflow: auto;
    }
    /deep/ .el-tab-pane{
        height: calc(100% - 16px);
    }
}
.el-scrollbar /deep/ .el-scrollbar__wrap{
  overflow: auto;
  overflow-x: hidden;
  margin-bottom: 0px!important;
}
</style>
